# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk, messagebox
import random
import time
import sqlite3
from datetime import datetime
import pygame
from tkinter import scrolledtext, messagebox,Toplevel,PhotoImage,CENTER,Label,BOTH,ttk
from zsm import *
import sys
import os

def resource_path(relative_path):
    path = os.path.join(sys._MEIPASS, relative_path) if hasattr(sys, '_MEIPASS') else os.path.join(os.path.abspath("."), relative_path)
    print(f"资源路径解析: {relative_path} => {path}")
    if not os.path.exists(path):
        raise FileNotFoundError(f"关键文件缺失: {path}")
    return path
class WhackAMole:
    def __init__(self, root):
        self.root = root
        self.root.title("+++超级打地鼠+++多动物版    by:风二西  2025.03.01")
        self.root.geometry("600x400")

        # 初始化声音引擎（仅保留打击音效）
        try:
            pygame.mixer.init()
            self.hit_sound = pygame.mixer.Sound(resource_path("hit.wav"))  # 关键修改
            print("音效文件路径:", resource_path("hit.wav"))
        except Exception as e:
            print(f"音效加载失败: {str(e)}")
            self.audio_available = False
        else:
            self.audio_available = True

        # 动物配置（概率总和为1）
        self.animals = [
            {'symbol': '🐭', 'score': 10, 'prob': 0.180, 'color': '#A0522D'},
            {'symbol': '🐰', 'score': 15, 'prob': 0.11, 'color': '#FFB6C1'},
            {'symbol': '🐹', 'score': 20, 'prob': 0.13, 'color': '#D2691E'},
            {'symbol': '🐯', 'score': 50, 'prob': 0.043, 'color': '#FF8C00'},
            {'symbol': '🦁', 'score': 60, 'prob': 0.032, 'color': '#FFD700'},
            {'symbol': '🐶', 'score': 25, 'prob': 0.07, 'color': '#CD853F'},
            {'symbol': '🐻', 'score': 35, 'prob': 0.065, 'color': '#8B4513'},
            {'symbol': '🐼', 'score': 40, 'prob': 0.054, 'color': '#000000'},
            {'symbol': '🐮', 'score': 20, 'prob': 0.108, 'color': '#000000'},
            {'symbol': '🐧', 'score': 45, 'prob': 0.032, 'color': '#000080'},
            {'symbol': '🐸', 'score': 30, 'prob': 0.043, 'color': '#32CD32'},
            {'symbol': '🦄', 'score': 100, 'prob': 0.011, 'color': '#FF69B4'},
            {'symbol': '🐷', 'score': 15, 'prob': 0.022, 'color': '#FFC0CB'},
            {'symbol': '🐍', 'score': 60, 'prob': 0.011, 'color': '#228B22'},
            {'symbol': '🐴', 'score': 30, 'prob': 0.022, 'color': '#8B4513'},
            {'symbol': '🐔', 'score': 15, 'prob': 0.022, 'color': '#FF0000'},
            {'symbol': '🐑', 'score': 25, 'prob': 0.025, 'color': '#000000'},
            {'symbol': '🦊', 'score': 45, 'prob': 0.015, 'color': '#FF4500'},
            {'symbol': '🐳', 'score': 80, 'prob': 0.005, 'color': '#4682B4'},
        ]

        # 游戏参数
        self.durations = [30, 60, 120, 300,600,1800]
        self.game_duration = tk.IntVar(value=30)
        self.hole_count = 9
        self.mole_show_time = 2000  # 动物显示时间2秒
        self.score = 0

        # 数据库初始化
        self.conn = sqlite3.connect('game_records.db')
        self.cursor = self.conn.cursor()
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS records
                            (id INTEGER PRIMARY KEY AUTOINCREMENT,
                             score INTEGER,
                             duration INTEGER,
                             timestamp DATETIME)''')

        # 初始化界面
        self.create_widgets()
        self.setup_holes()

        # 游戏状态
        self.game_active = False
        self.start_time = None

    def create_widgets(self):
        """创建界面组件"""
        top_frame = ttk.Frame(self.root)
        top_frame.pack(pady=10, fill=tk.X)

        # 左侧信息区
        left_info = ttk.Frame(top_frame)
        self.score_label = ttk.Label(left_info, text="分数: 0", font=('微软雅黑', 12))
        self.score_label.pack(side=tk.LEFT, padx=5)
        self.time_label = ttk.Label(left_info, text="剩余时间: 30", font=('微软雅黑', 12))
        self.time_label.pack(side=tk.LEFT, padx=15)
        left_info.pack(side=tk.LEFT)

        # 中间控制区
        center_control = ttk.Frame(top_frame)
        ttk.Label(center_control, text="游戏时长：").pack(side=tk.LEFT)
        self.duration_combo = ttk.Combobox(center_control,
                                           textvariable=self.game_duration,
                                           values=self.durations,
                                           width=6,
                                           state='readonly')
        self.duration_combo.pack(side=tk.LEFT, padx=5)

        self.start_btn = ttk.Button(center_control, text="开始游戏",
                                    command=self.start_game, width=8)
        self.start_btn.pack(side=tk.LEFT, padx=8)

        # 功能按钮
        ttk.Button(center_control, text="🏆积分榜", command=self.show_records, width=8).pack(side=tk.LEFT, padx=3)
        ttk.Button(center_control, text="赞赏作者", command=self.show_support, width=10).pack(side=tk.LEFT, padx=3)
        center_control.pack(side=tk.LEFT)

        # 游戏区域
        self.game_frame = ttk.Frame(self.root)
        self.game_frame.pack(pady=15)

    def setup_holes(self):
        """初始化地洞布局"""
        self.holes = []
        for i in range(9):
            hole = tk.Label(self.game_frame,
                            text='🕳️',
                            font=('Segoe UI Emoji', 48),
                            width=3, height=1,
                            padx=8, pady=8)
            row = i // 3
            col = i % 3
            hole.grid(row=row, column=col)
            hole.bind('<Button-1>', lambda e, idx=i: self.whack(e, idx))
            self.holes.append({
                'widget': hole,
                'active': False,
                'animal': None,
                'cooldown': 0  # 冷却时间（毫秒时间戳）
            })

    def get_random_animal(self):
        """随机获取动物"""
        r = random.random()
        cumulative = 0
        for animal in self.animals:
            cumulative += animal['prob']
            if r < cumulative:
                return animal
        return self.animals[0]

    def start_game(self):
        """开始游戏"""
        self.game_active = True
        self.score = 0
        self.start_time = time.time()
        self.update_score()
        self.start_btn.config(state='disabled')
        self.schedule_mole()
        self.update_timer()

    def schedule_mole(self):
        """安排下一个地鼠出现"""
        if self.game_active:
            self.root.after(random.randint(500, 1500), self.show_random_mole)

    def show_random_mole(self):
        """显示随机地鼠（带冷却检查）"""
        if not self.game_active:
            return

        current_time = time.time() * 1000  # 当前时间（毫秒）
        available = [i for i, h in enumerate(self.holes)
                     if not h['active'] and current_time > h['cooldown']]

        if available:
            idx = random.choice(available)
            animal = self.get_random_animal()

            self.holes[idx].update({
                'active': True,
                'animal': animal
            })

            # 更新显示
            self.holes[idx]['widget'].config(
                text=animal['symbol'],
                font=('Segoe UI Emoji', 48),
                fg=animal['color']
            )
            # 2秒后自动消失
            self.root.after(self.mole_show_time, lambda: self.hide_mole(idx))

        self.schedule_mole()

    def hide_mole(self, idx):
        """隐藏地鼠（仅用于自然消失的情况）"""
        if self.holes[idx]['active']:
            self.holes[idx]['widget'].config(text='🕳️', font=('Segoe UI Emoji', 48))
            self.holes[idx]['active'] = False
            # 设置冷却时间为当前时间+2000ms
            self.holes[idx]['cooldown'] = time.time() * 1000 + 2000

    def whack(self, event, idx):
        """打击处理"""
        if self.game_active and self.holes[idx]['active']:
            # 播放音效
            if self.audio_available:
                self.hit_sound.play()

            # 立即隐藏动物
            animal = self.holes[idx]['animal']
            self.score += animal['score']

            # 设置爆炸效果并在500ms后恢复地洞
            self.holes[idx]['widget'].config(text='💥', fg='red')
            self.holes[idx]['active'] = False
            # 设置冷却时间为当前时间+2000ms
            self.holes[idx]['cooldown'] = time.time() * 1000 + 2000
            # 0.5秒后恢复地洞外观
            self.root.after(500, lambda: self.reset_hole(idx))
            self.update_score()

    def reset_hole(self, idx):
        self.holes[idx]['widget'].config(
            text='🕳️',
            fg='black'  # 强制设置为黑色
        )
    def update_score(self):
        """更新分数显示"""
        self.score_label.config(text=f"分数: {self.score}")

    def update_timer(self):
        """更新计时器"""
        if self.game_active:
            elapsed = time.time() - self.start_time
            remaining = self.game_duration.get() - int(elapsed)
            self.time_label.config(text=f"剩余时间: {remaining}")

            if remaining <= 0:
                self.end_game()
            else:
                self.root.after(1000, self.update_timer)

    def end_game(self):
        """结束游戏"""
        self.game_active = False
        self.start_btn.config(state='normal')

        # 保存记录
        self.cursor.execute('INSERT INTO records (score, duration, timestamp) VALUES (?,?,?)',
                            (self.score, self.game_duration.get(), datetime.now()))
        self.conn.commit()

        # 重置所有地洞
        for h in self.holes:
            if h['active']:
                self.hide_mole(self.holes.index(h))
        messagebox.showinfo("游戏结束", f"游戏结束！最终得分: {self.score}")

    def show_records(self):
        """显示积分榜"""
        records_window = tk.Toplevel(self.root)
        records_window.title("游戏记录")
        records_window.geometry("400x300")

        tree = ttk.Treeview(records_window, columns=('time', 'duration', 'score'), show='headings')
        tree.heading('time', text='时间')
        tree.heading('duration', text='时长(秒)')
        tree.heading('score', text='得分')
        tree.column('time', width=150)
        tree.column('duration', width=80)
        tree.column('score', width=80)

        self.cursor.execute("SELECT timestamp, duration, score FROM records ORDER BY timestamp DESC LIMIT 30")
        for row in self.cursor.fetchall():
            tree.insert('', 'end', values=(row[0][:19], row[1], row[2]))

        scrollbar = ttk.Scrollbar(records_window, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=scrollbar.set)
        tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

    def show_support(self):
        """显示支持信息"""
        self.zsm_windows = Toplevel(self.root)
        # 替换窗口浮于上方
        self.zsm_windows.wm_attributes("-topmost", 1)
        self.zsm_windows.title('赞赏作者')
        self.photo1 = PhotoImage(data=zsm123)
        self.zsm1 = Label(self.zsm_windows, image=self.photo1,
                          compound=CENTER)
        self.zsm1.pack(fill=BOTH, expand=True)

if __name__ == "__main__":
    root = tk.Tk()
    game = WhackAMole(root)
    root.mainloop()